/**
 * 
 */
package com.idle.util;

import java.io.File;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.widget.Toast;

/*******
 * 
 *******/
public class UriUtil {
	/**
	 * such as  content://media/external/images/media/79147; path is /external/images/media/79147
	 * @param mContext
	 * @param file
	 * @param mListener
	 */
	public static void getUrifromFile(Context mContext, File file, final ScanFileListener mListener) {
		MediaScannerConnection.scanFile(mContext,
                new String[] {
                    file.toString()
                }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(final String path, final Uri uri) {
                        if (mListener != null) {
                        	mListener.onScanCompleted(path, uri);
                        }
                    }
                });
	}

	/**
	 * @param path
	 * @return such as file:///mnt/sdcard/1.jpg; path is /mnt/sdcard/1.jpg
	 */
	public static Uri fromPath(String path) {
		return Uri.fromFile(new File(path));
	}

	public static String getPathFromUri(Context context, Uri uri) {
		if (uri.toString().startsWith("file://")) {
			return uri.toString().substring(7);
		}
		String[] proj = { MediaStore.Images.Media.DATA };
	    CursorLoader loader = new CursorLoader(context, uri, proj, null, null, null);
	    Cursor cursor = loader.loadInBackground();
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    String path = cursor.getString(column_index);
	    cursor.close();
	    return path;
	}
	
	public interface ScanFileListener{
		void onScanCompleted(final String path, final Uri uri);
	}
}
